package upload

import (
	"bufio"
	"fdfs/util"
	"io"
	"log"
	"mime/multipart"
	"os"
	"strconv"
)

func PathExists(path string) (bool, error) {

	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func CreateDir() (string, string, chan int) {
	path, url := GetPath()
	bl, err := PathExists(path)
	if err != nil {
		panic("创建文件夹失败")
	}
	ch := make(chan int)
	Pool.Submit(func() {
		if !bl {
			os.MkdirAll(path, os.FileMode(os.ModePerm))
		}
		ch <- 1
	})
	return path, url, ch
}

func UploadUtils(file multipart.File, h *multipart.FileHeader) string {
	fileName := h.Filename
	expr := GetImgType(fileName)
	node, err := util.NewWorker(1)
	if err != nil {
		panic("id获取失败")
	}
	path, url, ch := CreateDir()
	defer close(ch)
	imgId := strconv.FormatInt(node.GetId(), 10)
	fakePath := path + imgId + expr
	url = url + imgId + expr
	log.Println("真实路径 path", fakePath)
	ok := make(chan int)
	defer close(ok)
	Pool.Submit(func() {
		<-ch
		createFile, err := os.Create(fakePath)
		if err != nil {
			log.Println("创建文件失败")
		}
		wt := bufio.NewWriter(createFile)
		io.Copy(wt, file)
		createFile.Close()
		ok <- 1
	})
	<-ok
	return url
}
